package com.treasure.service.common.controller;

import java.io.UnsupportedEncodingException;
import java.util.concurrent.TimeUnit;

import com.treasure.service.third.utils.TokenConfig;
import com.treasure.service.third.utils.UserToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.treasure.service.annotation.LogInfo;
import com.treasure.service.enums.CodeEnum;
import com.treasure.service.enums.RedisKeys;
import com.treasure.service.result.ResponseResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

/** 
* @ClassName    : InviteController 
* @author       : panxingwu 
* @date         : 2018年11月29日 下午10:57:34 
* @Description  : 弹窗接口
*/
@Api(value = "弹窗控制",description = "控制前端是否弹窗")
@RestController
@RequestMapping("/dialog/v1")
@Slf4j
public class DialogController {

    @Autowired
    RedisTemplate<String,String> redisTemplate;
    @ApiOperation(value = "获取弹窗配置", notes = "获取弹窗配置")
    @LogInfo(log = "获取弹窗配置",isPrint = true)
    @PostMapping("/getConfig")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "type", value = "类型（1：首页弹窗）", required = true, dataType = "String", paramType = "query"),
    })
    public ResponseEntity<ResponseResult> getConfig(@RequestParam(value = "type") String type) throws UnsupportedEncodingException {
        log.info("获取弹窗配置参数：type="+type);
        UserToken userToken = TokenConfig.getTokenByHeader();
        String json = (String) redisTemplate.opsForHash().get(RedisKeys.TOKEN.build("USERDIALOG"),userToken.getUserId()+"");
        String ifDialog = "Y";
        log.info("用户信息:"+JSON.toJSONString(userToken));
        if(userToken.getIsMember() == 1) {
        	ifDialog="N";
        };
        if("HASALERT".equals(json)) {
        	ifDialog="N";
        }
        if("Y".equals(ifDialog)) {
            redisTemplate.opsForHash().put(RedisKeys.TOKEN.build("USERDIALOG"),userToken.getUserId()+"","HASALERT");
            redisTemplate.expire(RedisKeys.TOKEN.build("USERDIALOG"),2,TimeUnit.HOURS);//设置超时时间10秒 第三个参数控制时间单位，详情查看TimeUnit
        }
        log.info("获取弹窗配置结果：ifDialog="+ifDialog);
        return  ResponseEntity.ok(new ResponseResult(CodeEnum.SUCCESS,ifDialog));

    }
}
